package com.ll.module_translate.repository

import com.blankj.utilcode.util.LogUtils
import com.ll.module_translate.entity.TResult
import com.ll.module_translate.entity.TranslateResult
import com.ll.module_translate.net.ApiTranslate
import com.ll.module_translate.translateAppId
import com.ll.module_translate.translateSecurityKey
import com.ll.module_translate.translateUrl
import com.ll.module_translate.utils.ErrorCode
import com.ll.module_translate.utils.MD5
import com.ll.module_translate.utils.TransLanguage
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * @Author: ll
 * @CreateTime: 2021/10/29 10:17
 */
object TranslateRepository {

    private val apiTranslate by lazy {
        Retrofit.Builder()
            .client(
                OkHttpClient().newBuilder()
                    .addInterceptor {
                        val request = it.request().newBuilder().build()
                        LogUtils.d(
                            request.url, request.body, request.headers
                        )
                        it.proceed(request)
                    }
                    .build()
            )
            .baseUrl(translateUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiTranslate::class.java)
    }


    suspend fun translate(
        query: String,
        from: String = TransLanguage.CHINESE,
        to: String = TransLanguage.RUSSIAN,
        appId: String = translateAppId,
        salt: String = System.currentTimeMillis().toString(),
        sign: String = MD5.md5(
            translateAppId +
                    query +
                    salt +
                    translateSecurityKey
        )
    ): TResult<TranslateResult> {
        apiTranslate.translate(
            query,
            from,
            to,
            appId,
            salt,
            sign
        ).apply {
            LogUtils.d(error_code, error_msg)

            return if (error_code.isNullOrEmpty()) {
                TResult.Success(from, to, trans_result)
            } else {
                TResult.Error(error_code!!, ErrorCode.getError(error_code!!))
            }
        }
    }


}